package com.sgu6.sgu6_machine.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import com.linheimx.app.library.charts.LineChart;
import com.linheimx.app.library.data.Entry;
import com.linheimx.app.library.data.Line;
import com.linheimx.app.library.data.Lines;
import com.linheimx.app.library.model.XAxis;
import com.linheimx.app.library.model.YAxis;
import com.sgu6.middleware.enums.MachineCmdEnum;
import com.sgu6.middleware.util.HexUtil;
import com.sgu6.serialport.manager.SerialPortManager;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.base.BaseA;
import com.sgu6.sgu6_machine.common.CmdTranslator;
import com.sgu6.sgu6_machine.event.CmdEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.sgu6.sgu6_machine.container.ComContainer.isRecordHeart;

public class TempCurveA extends BaseA {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.chart)
    LineChart chart;

    public List<Double> verTemp = new ArrayList<>(); //纵封温度
    public List<Double> horTemp = new ArrayList<>(); //横封温度

    Timer heartTimer;
    TimerTask heartTask;
    CmdTranslator mp = new CmdTranslator();
    Line horLine = new Line();
    Line verLine = new Line();
    List<Entry> horList = new ArrayList<>();
    List<Entry> verList = new ArrayList<>();
    Lines lines = new Lines();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temp_curve);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initUI();
    }

    @Override
    public void initUI() {
        initToolbar();
        initChart();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return true;
    }


    private void initToolbar() {
        toolbar.setTitle("温度曲线");
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setBackgroundResource(R.color.colorPrimaryDark);
        setSupportActionBar(toolbar);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
    }

    private void initChart() {
        // step1: 设置x,y轴
        XAxis xAxis = chart.get_XAxis();
//        xAxis.set_unit("单位：s");
//        xAxis.set_ValueAdapter(new DefaultValueAdapter(1));

        YAxis yAxis = chart.get_YAxis();
//        yAxis.set_unit("单位：m");
//        yAxis.set_ValueAdapter(new DefaultValueAdapter(1));// 默认精度到小数点后2位,现在修改为3位精度
        // step2: 为一条数据线添加数据

        horLine.setEntries(horList);
        horLine.setLineColor(Color.RED);

        verLine.setEntries(verList);
        verLine.setLineColor(Color.BLUE);

        // step3: 将数据放到 lineChart上
        lines.addLine(horLine);
        lines.addLine(verLine);
        chart.setLines(lines);


    }

    @OnClick({R.id.btn_start, R.id.btn_stop})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_start:
                isRecordHeart = true;
                startMachineHeartTimer();
                break;
            case R.id.btn_stop:
                isRecordHeart = false;
                stopMachineHeartTimer();
                break;
        }
    }

    public void startMachineHeartTimer() {
        if (heartTimer == null && heartTask == null) {
            heartTimer = new Timer();
            heartTask = new TimerTask() {
                @Override
                public void run() {
                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.心跳包.code()));
                }
            };
//        heartTimer.schedule(heartTask, 500, Constant.socketHeartbeatTime * 1000);
            heartTimer.schedule(heartTask, 500, 1000);
        }
    }

    public void stopMachineHeartTimer() {
        if (heartTask != null) {
            heartTask.cancel();
            heartTask = null;
        }
        heartTimer = null;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHeartbeatEvent(CmdEvent event) {
        if (event.type == 1 && event.cmd[5] == 0x02) {
            String strCmd = HexUtil.Bytes2HexString(event.cmd);
            if (isRecordHeart && strCmd.substring(10, 12).equals("02")) {
                HashMap<String, Long> status = mp.translateHeart2Map(strCmd);
                try {
                    double a = status.get("hTemp") * 0.1;
                    double b = status.get("vTemp") * 0.1;
                    horTemp.add(a);
                    verTemp.add(b);
                    horList.add(new Entry(horTemp.size() - 1, a));
                    verList.add(new Entry(verTemp.size() - 1, b));
                    horLine.setEntries(horList);
                    verLine.setEntries(verList);
                    chart.notifyDataChanged();
                    chart.invalidate();
                } catch (Exception e) {
                    Log.i(TAG, "onHeartbeatEvent: " + e.getLocalizedMessage());
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        isRecordHeart = false;
        stopMachineHeartTimer();
    }

}
